package day14;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

//需求：取ArrayList中的重复的元素，并且存的是自定义的对象
/*
 * 注意：List集合特殊之处
 * List集合判断元素是否相同，依据是元素的equals方法。
 * 不论是包含contains、remove等方法都是依赖于元素的equals方法
 */
public class ArrayListTest2<E> {

	public static void main(String[] args) {
		ArrayListTest2<Person> list = new ArrayListTest2<Person>();
		List<Person> arrayList = new ArrayList<Person>();
		arrayList.add(new Person("wangwu", 21));
		arrayList.add(new Person("lisi", 20));
		arrayList.add(new Person("zhangsan", 19));
		arrayList.add(new Person("lisi", 21));
		arrayList.add(new Person("lisi", 21));
		arrayList.add(new Person("zhaoliu", 24));
		arrayList.add(new Person("wangwu", 21));
		arrayList = list.singleElement(arrayList);
		for (Person person : arrayList) {
			System.out.println(person);
		}
	}
	
	public List<E> singleElement(List<E> list) {
		
		List<E> newList = new ArrayList<E>();
		for (ListIterator<E> iterator = list.listIterator(); iterator.hasNext();) {
			E e = iterator.next();
			if (!newList.contains(e)) {
				newList.add(e);
			}
		}
		return newList;
	} 
}
//需求2：如同人，同姓名同年龄就视为同一个人，视为重复的元素

class Person {
	
	public Person() {

	}

	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}
	
	private String name;
	
	private int age;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + "]";
	}

	//复写Person类的equals方法
	@Override
	public boolean equals(Object obj) {
		
		if (!(obj instanceof Person)) {
			return false; // 或者直接抛异常
		}
		Person person  = (Person) obj;
		return this.name.equals(person.name) && this.age == person.age;
	}

	@Override
	public int hashCode() {
		return this.name.hashCode() + this.age * 37;
	}
	
	
	
}
